﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Barbar.UrlGuard.Dal;
using System.Text.RegularExpressions;
using System.Globalization;
using Barbar.UrlGuard.BL;

namespace Barbar.UrlGuard.Controls {
  public partial class EmailSettings : UserControl {
    public EmailSettings() {
      InitializeComponent();
    }

    public bool DoValidate() {
      if (!this.Enabled || (ValidateSmtp() && ValidateEmailList())) {
        errorProvider.Clear();
        return true;
      }
      return false;
    }

    private bool ValidateSmtp() {
      if (string.IsNullOrEmpty(txtSmtp.Text)) {
        errorProvider.SetError(txtSmtp, "Smtp server cannot be left empty.");
        return false;
      }

      bool isValidAddress = false;
      try {
        IPAddress[] addressed = Dns.GetHostAddresses(txtSmtp.Text);
        if (addressed != null && addressed.Length > 0)
          isValidAddress = true;
      } catch {
      }

      if (!isValidAddress) {
        errorProvider.SetError(txtSmtp, "Unable to resolve smtp server address.");
        return false;
      }
      return true;
    }

    private bool ValidateEmailList() {
      if (string.IsNullOrEmpty(txtEmails.Text)) {
        errorProvider.SetError(txtEmails, "Mailing list cannot be left empty.");
        return false;
      }

      const string emailPattern = @"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}";
      string commaPattern = string.Format(CultureInfo.InvariantCulture, @"^{0}(\s*,\s*{0})*$", emailPattern);

      Regex regex = new Regex(commaPattern, RegexOptions.IgnoreCase);
      if (!regex.IsMatch(txtEmails.Text)) {
        errorProvider.SetError(txtEmails, "One or more emails are not valid.");
        return false;
      }
      return true;
    }

    private void chxAuthenticate_CheckedChanged(object sender, EventArgs e) {
      txtUserName.Enabled = chxAuthenticate.Checked;
      txtPassword.Enabled = chxAuthenticate.Checked;
    }

    public void SetEmailAlert(EmailAlertSettings emailAlertSettings) {
      if (emailAlertSettings == null) {
        txtUserName.Text = string.Empty;
        txtPassword.Text = string.Empty;
        txtEmails.Text = string.Empty;
        txtSmtp.Text = string.Empty;
        txtPort.Value = 25;
        chxUseSSL.Checked = false;
        chxAuthenticate.Checked = false;
      } else {
        txtUserName.Text = emailAlertSettings.UserName;
        txtPassword.Text = emailAlertSettings.Password;
        txtEmails.Text = emailAlertSettings.EmailsAsText;
        txtSmtp.Text = emailAlertSettings.SmtpServer;
        txtPort.Value = emailAlertSettings.Port;
        chxUseSSL.Checked = emailAlertSettings.UseSsl;
        chxAuthenticate.Checked = emailAlertSettings.AuthenticateSmtp;
      }
    }

    public EmailAlertSettings GetEmailAlert() {
      return new EmailAlertSettings() {
        AuthenticateSmtp = chxAuthenticate.Checked,
        EmailsAsText = txtEmails.Text,
        Password = txtPassword.Text,
        SmtpServer = txtSmtp.Text,
        UserName = txtUserName.Text,
        Port = (int)txtPort.Value,
        UseSsl = chxUseSSL.Checked
      };
    }

    private void btnTest_Click(object sender, EventArgs e) {
      IEmailAlertService emailAlertService = ServiceLocator.Instance.Resolve<IEmailAlertService>();
      emailAlertService.SendEmailTest(GetEmailAlert());
    }

    private void btnPrefillGmailSettings_Click(object sender, EventArgs e) {
      txtPort.Value = 587;
      txtSmtp.Text = "smtp.gmail.com";
      chxUseSSL.Checked = true;
    }

  }
}
